// backend/src/mappers/user/roleMapper.js
import sequelize from "../../config/db.js";

/**
 * @description 检查角色是否已存在
 * @param {Object} roleData - 角色数据
 * @returns {Promise<Object|null>} 返回现有角色或 null
 */
const existingRole = async (roleData) => {
    const [existingRole] = await sequelize.query(
        `SELECT * FROM sys_role WHERE role_name = :role_name AND (isDeleted = 1 OR isDeleted = 0)`,
        {
            replacements: { role_name: roleData.role_name }
        }
    );
    return existingRole;
};

/**
 * @description 创建角色
 * @param {Object} roleData - 角色数据
 * @returns {Promise<void>}
 */
const createRole = async (roleData) => {
    await sequelize.query(
        `INSERT INTO sys_role (role_name, isDeleted) VALUES (:role_name, :isDeleted)`,
        {
            replacements: {
                role_name: roleData.role_name,
                isDeleted: roleData.isDeleted !== undefined ? roleData.isDeleted : 1
            }
        }
    );
};

/**
 * @description 获取所有角色
 * @returns {Promise<Array>} 返回角色列表
 */
const getAllRoles = async () => {
    const [roles] = await sequelize.query(
        `SELECT * FROM sys_role WHERE isDeleted = 1`
    );
    return roles;
};

/**
 * @description 通过角色 ID 获取角色
 * @param {number} roleId - 角色 ID
 * @returns {Promise<Object|null>} 返回角色信息或 null
 */
const getRoleById = async (roleId) => {
    const [role] = await sequelize.query(
        `SELECT * FROM sys_role WHERE role_id = :roleId AND isDeleted = 1`,
        {
            replacements: { roleId }
        }
    );
    return role.length > 0 ? role[0] : null;
};

/**
 * @description 更新角色
 * @param {number} roleId - 角色 ID
 * @param {Object} roleData - 更新的数据
 * @returns {Promise<void>}
 */
const updateRole = async (roleId, roleData) => {
    await sequelize.query(
        `UPDATE sys_role SET role_name = :role_name, isDeleted = :isDeleted WHERE role_id = :roleId AND isDeleted = 1`,
        {
            replacements: {
                role_name: roleData.role_name,
                isDeleted: roleData.isDeleted !== undefined ? roleData.isDeleted : 1,
                roleId
            }
        }
    );
};

/**
 * @description 逻辑删除角色
 * @param {Array<number>} roleIds - 角色 ID 列表
 * @returns {Promise<void>}
 */
const deleteRole = async (roleIds) => {
    await sequelize.query(
        `UPDATE sys_role SET isDeleted = 0 WHERE role_id IN (:roleIds)`,
        {
            replacements: { roleIds }
        }
    );
};

export default { existingRole, createRole, getAllRoles, getRoleById, updateRole, deleteRole };
